//
//  Theme.swift
//  HeadlineNews
//
//  Created by han on 2019/7/24.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit
import SSZipArchive

// 切换主题：本地切换固定主题，切换网络下载主题。
// 使用网络下载主题时，需要判断是否是最新的。是否显示。
let kThemeType = "kThemeType"
// 用来保存是否存在localTheme，或者localTheme是否需要更新
let kCustomThemeLocalSign = "kCustomThemeLocalSign"

enum HeadlineTheme: Int {
    case `default` = 0
    case night = 1
    case custom = 2
    
    static var before = HeadlineTheme.default
    static var current = HeadlineTheme.default
    
    static func switchTo(_ theme: HeadlineTheme) {
        before = current
        current = theme
        UserDefaults.set(theme.rawValue, forKey: kThemeType)
        switch theme {
        case .default:
            ThemeManager.setTheme(name: "Theme_default", themeConfig: ThemeConfig(themeType: .txt, themePath: .mainBundle))
            ThemeManager.currentThemeIndex = 0
        case .night:
            ThemeManager.setTheme(name: "Theme_night", themeConfig: ThemeConfig(themeType: .txt, themePath: .mainBundle))
            ThemeManager.currentThemeIndex = 1
        case .custom:
            ThemeManager.setTheme(name: "Blue", themeConfig: ThemeConfig(themeType: .plist, themePath: .sandbox(blueDiretory)))
        }
    }
    static func initLocalTheme() {
        let theme = UserDefaults.integer(forKey: kThemeType)
        switchTo(HeadlineTheme(rawValue: theme)!)
    }
    
    static var customSign: String?
    
}

private let downloadUrl = "https://github.com/wxxsw/SwiftThemeResources/blob/master/20170128/Blue.zip?raw=true"

extension HeadlineTheme {
    // 网络下载
    static func downloadBlueTask(_ handler: @escaping (_ isSuccess: Bool) -> Void) {
        let task = URLSession.shared.downloadTask(with: Foundation.URL(string: downloadUrl)!, completionHandler: { location, response, error in
            guard let location = location , error == nil else {
                DispatchQueue.main.async {
                    handler(false)
                }
                return
            }
            
            let manager = FileManager.default
            let zipPath = FileURL.cachesURL.appendingPathComponent("Blue.zip")
            
            _ = try? manager.removeItem(at: zipPath)
            _ = try? manager.moveItem(at: location, to: zipPath)
            
            let isSuccess = SSZipArchive.unzipFile(atPath: zipPath.path,  toDestination: unzipPath.path)
            DispatchQueue.main.async {
                handler(isSuccess)
            }
        })
        
        task.resume()
    }
    
    static func isBlueThemeExist() -> Bool {
        return FileManager.default.fileExists(atPath: blueDiretory.path)
    }
    
    static let blueDiretory : URL = unzipPath.appendingPathComponent("Blue/")
    static let unzipPath    : URL = FileURL.libraryURL.appendingPathComponent("Themes/20170128")
}

// MARK: 处理本地下载的Theme
extension HeadlineTheme {
   
    static func handleLocalTheme() {
        
    }
    
 /*
     流程：进入app
     流程1: 判断localSign，为空，则显示默认Theme；不为空则加载customTheme
     流程2: 网络请求 返回customSign，判断是否加载CustomTheme。不加载则localSign置空，通知使用本地默认Theme，清除本地缓存的CustomTheme；加载，则判断 localSign 和 customSign 是否一样，一样则加载缓存的主题，不一样下载新的，通知使用新的皮肤，删除旧的缓存。
 */
    
}
